package com.example.utils.util;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.springframework.util.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *  TODO  文件读取 MD5 码
 * @Author 江
 * @Date 2021/10/13 下午 16:04
 */
public class MD5Check {
    public static String getFileMD5(String filePath) throws Exception{
        File file = new File(filePath);
        InputStream in = new FileInputStream(file);
        MessageDigest digest = MessageDigest.getInstance("MD5");  ;
        byte buffer[] = new byte[1024];
        int len;
        while((len = in.read(buffer))!=-1){
            digest.update(buffer, 0, len);
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    /**
     *  TODO  spring自带工具包DigestUtils进行MD5加密
     * @Author 江
     */
    public static String getMD5(String pd){
        // spring自带工具包DigestUtils
        return DigestUtils.md5DigestAsHex(pd.getBytes());
    }

    /**
     *  TODO  java自带jar工具MessageDigest实现MD5加密
     * @Author 江
     */
    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static void main(String[] args) throws Throwable{
        //String f1 = getFileMD5("C:\\Users\\xiaojiang\\Downloads\\gitlab-ce-13.0.12-ce.0.el6.x86_64.rpm");
        //System.out.println(f1);
        //System.out.println(f1.equals("2afc8e3f4c0ae573204341f25717f7d8"));

        //String s = stringToMD5("1234");
        //System.out.println(s);


        /**

         * 创建一个插入对象为一亿，误报率为0.01%的布隆过滤器

         * 不存在一定不存在

         * 存在不一定存在

         * ----------------

         *  Funnel 对象：预估的元素个数，误判率

         *  mightContain ：方法判断元素是否存在

         */

        BloomFilter<CharSequence> bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.forName("utf-8")), 100000000, 0.0001);

        bloomFilter.put("死");

        bloomFilter.put("磕");

        bloomFilter.put("Redis");

        System.out.println(bloomFilter.mightContain("Redis"));

        System.out.println(bloomFilter.mightContain("Java"));

    }

}
